<template>
  <div class="publish-content">
    <baseTable
      ref="tableRef"
      :page.sync="page"
      :cols="tableCols"
      :data="tableData"
      :hasCheck="true"
      @select-change="handleSelectionChange"
    >
      <template #head>
        <div class="head">
          <div class="search">
            <el-cascader
              v-model="areaInfo"
              :options="cityList"
              :props="casxaderProps"
              placeholder="体检城市"
              class="area-cascader"
              :show-all-levels="false"
              @change="handleChangeArea"
              clearable
            ></el-cascader>
            <el-select
              class="bar-left-select ml-10"
              v-model="params.year"
              placeholder="体检年份"
              clearable
            >
              <el-option
                v-for="item in yearOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
            <el-select
              v-model="params.status"
              placeholder="填报状态"
              clearable
              class="bar-left-select"
            >
              <el-option
                v-for="(item, index) in statusList"
                :key="index"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
            <el-input
              placeholder="请输入任务名称、体系名称"
              v-model="params.keywords"
            >
              <i
                slot="suffix"
                class="el-input__icon el-icon-search cursor-pointer"
                @click="getTaskListData"
              ></i>
            </el-input>
          </div>
          <div>
            <el-button
              type="primary"
              icon="el-icon-download"
              @click="handleDownloadClick"
              v-if="currentUser?.hasPermission(PERMISSIONS.数据填报下载)"
            >
              {{
                currentUser?.getButtonName(PERMISSIONS.数据填报下载)
              }}</el-button
            >
          </div>
        </div>
      </template>
      <template #cols>
        <el-table-column label="基本指标填报进度">
          <template slot-scope="scope">
            {{ scope.row.baseCompleteCount }}/{{
              scope.row.baseAllCount
            }}</template
          >
        </el-table-column>
        <el-table-column label="特色指标填报进度">
          <template slot-scope="scope">
            {{ scope.row.specialCompleteCount }}/{{
              scope.row.specialAllCount
            }}</template
          >
        </el-table-column>
        <el-table-column label="填报状态" align="center">
          <template slot-scope="scope">
            <el-tag
              :color="getStatusInfo(scope.row.status).bgColor"
              size="small"
              :style="{
                color: getStatusInfo(scope.row.status).color,
                border: 'none',
              }"
              disable-transitions
              >{{ getStatusInfo(scope.row.status).statusText }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="更新时间">
          <template slot-scope="scope">
            {{
              scope.row.createTime ? scope.row.createTime : scope.row.updateTime
            }}</template
          >
        </el-table-column>
        <el-table-column label="操作" width="180" align="center">
          <template slot-scope="scope">
            <el-link
              slot="reference"
              class="mr-10"
              type="primary"
              v-if="currentUser?.hasPermission(PERMISSIONS.数据填报详情)"
              @click="
                goEdit(
                  scope.row.pkid,
                  '',
                  scope.row.status,
                  scope.row.regionId,
                  scope.row.taskId
                )
              "
              :underline="false"
              >{{
                currentUser?.getButtonName(PERMISSIONS.数据填报详情)
              }}</el-link
            >
            <el-popconfirm
              title="确定退回该项？"
              @confirm="handleRemove(scope.row, scope.$index)"
            >
              <el-link
                v-if="
                  scope.row.status == -1 &&
                  currentUser?.hasPermission(PERMISSIONS.数据填报退回)
                "
                slot="reference"
                type="danger"
                :underline="false"
                >{{
                  currentUser?.getButtonName(PERMISSIONS.数据填报退回)
                }}</el-link
              >
            </el-popconfirm>
            <el-link
              slot="reference"
              v-if="
                scope.row.status != -1 &&
                scope.row.status != 2 &&
                beforeDeadline(scope.row.completeTime) &&
                currentUser?.hasPermission(PERMISSIONS.数据填报填报)
              "
              type="primary"
              @click="
                goEdit(
                  scope.row.pkid,
                  true,
                  scope.row.status,
                  scope.row.regionId,
                  scope.row.taskId
                )
              "
              :underline="false"
              >{{
                currentUser?.getButtonName(PERMISSIONS.数据填报填报)
              }}</el-link
            >
          </template>
        </el-table-column>
      </template>
    </baseTable>
  </div>
</template>

<script>
import baseTable from '@c/base-table'
import { getTaskList } from '@/api/data-converge'
import { getAreaList, getYearList } from '@api/indicator-manage'
import { mapGetters } from 'vuex'
import { queryArea } from '@api/question'
import {
  addTaskApply,
  exportExcel,
  exportWrite,
  queryBaseIndexPull,
  queryTask,
  queryTaskFill,
} from '@api/city-index'
import { getStatusInfo } from '../../../utils/ststus-color'
import { Message } from 'element-ui'
import { PERMISSIONS } from '@/common/user'
export default {
  name: 'publish',
  components: { baseTable },
  data() {
    return {
      PERMISSIONS,
      page: {
        pageIndex: 1,
        pageSize: 10,
        total: 0,
      },
      params: {
        areaId: null,
        districtId: null,
        year: null,
        keywords: null,
        status: null,
      },
      tableData: [],
      tableCols: [
        {
          prop: 'areaName',
          label: '体检城市',
        },
        {
          prop: 'taskName',
          label: '任务名称',
        },
        {
          prop: 'year',
          label: '体检年份',
        },
        {
          prop: 'completeTime',
          label: '完成时限',
          width: 160,
        },
      ],
      cityList: [],
      casxaderProps: {
        value: 'areaCode',
        label: 'areaName',
        checkStrictly: true,
        children: 'children',
      },
      areaInfo: [],
      yearOptions: [
        {
          value: '2021',
          label: '2021年',
        },
        {
          value: '2022',
          label: '2022年',
        },
        {
          value: '2023',
          label: '2023年',
        },
        {
          value: '2024',
          label: '2024年',
        },
      ],

      statusList: [
        { label: '待提交', value: 0 },
        { label: '待审核', value: 2 },
        { label: '已通过', value: -1 },
        { label: '退回', value: 1 },
        { label: '未填写', value: -2 },
      ],
      multipleSelection: [],
      isCq: false,
    }
  },
  created() {},
  mounted() {
    this.getTaskListData()
    queryArea({
      districtFlag: 'true',
    }).then((res) => {
      if (res.success) {
        const node = this.findNodeById(res.data, this.user.refId)
        this.cityList = this.removeChildrenAtLevel([node], 1)[0].children
      }
    })
    this.isCq = this.user.roleId === 'citymanager'
  },
  methods: {
    getStatusInfo,
    findNodeById(tree, targetId) {
      // 遍历树中的每个节点
      for (let i = 0; i < tree.length; i++) {
        // 检查当前节点的ID是否为目标ID
        if (tree[i].areaCode === targetId || tree[i].pkid === targetId) {
          // 如果是的话，返回当前节点
          return tree[i]
        }

        // 如果当前节点有子节点，则递归在子节点中查找
        if (tree[i].children && tree[i].children.length > 0) {
          const foundNode = this.findNodeById(tree[i].children, targetId)
          // 如果在子节点中找到了，则返回找到的节点
          if (foundNode !== undefined) {
            return foundNode
          }
        }
      }

      // 如果在树中没有找到目标ID，则返回undefined
      return undefined
    },
    beforeDeadline(time) {
      // 获取时间戳
      const now = new Date().getTime()
      const endTime = new Date(time).getTime()
      return now < endTime
    },
    handleChangeArea(val) {
      this.page.pageIndex = 1
      if (val.length === 1) {
        this.params.districtId = val[0]
        this.params.areaId = null
      } else {
        this.params.districtId = null
        this.params.areaId = val[val.length - 1]
      }
    },
    removeChildrenAtLevel(tree, targetLevel) {
      // 遍历树中的每个节点
      for (let i = 0; i < tree.length; i++) {
        // 检查当前节点的level是否为目标level
        if (tree[i].level === targetLevel) {
          // 如果是的话，移除children属性
          delete tree[i].children
        }

        // 如果当前节点还有子节点，并且子节点的level也为目标level，则递归处理子节点
        if (tree[i].children && tree[i].children.length > 0) {
          this.removeChildrenAtLevel(tree[i].children, targetLevel)
        }
      }

      return tree
    },
    handleSelectionChange(val) {
      const findData1 = val.filter((row) => {
        return row.status === -2
      })
      findData1.map((row) => {
        this.$refs.tableRef.$refs.tableRef.toggleRowSelection(row, false)
        this.$message.closeAll()
        this.$message({
          message: '不能选择未填报的数据',
          type: 'warning',
        })
      })
      const findTaskId = val.find((row) => {
        return row.state !== -2
      })
      if (findTaskId) {
        const findData2 = val.filter((row) => {
          return row.taskId !== findTaskId.taskId && row.status !== -2
        })
        findData2.map((row) => {
          this.$refs.tableRef.$refs.tableRef.toggleRowSelection(row, false)
          this.$message.closeAll()
          this.$message({
            message: '只能选择同一任务的数据',
            type: 'warning',
          })
        })
      }
      this.multipleSelection = val
    },
    handleDownloadClick() {
      const findTaskId = this.multipleSelection.find((row) => {
        return row.state !== -2
      })
      if (!findTaskId) {
        return Message.warning('请选择要导出的数据')
      }
      const arr = this.multipleSelection
        .filter((row) => {
          return row.taskId === findTaskId.taskId && row.status !== -2
        })
        .map((row) => {
          return row.pkid
        })
      if (!arr.length) {
        return Message.warning('请选择要导出的数据')
      }
      exportWrite(arr).then((res) => {
        if (res.data) {
          this.fileDownload(res.data, '指标数据.xlsx')
        }
      })
    },
    fileDownload(file, fileName = '下载文件', options) {
      // 创建隐藏的可下载链接
      let eleLink = document.createElement('a')
      eleLink.download = fileName
      eleLink.style.display = 'none'
      // 字符内容转变成blob地址
      let blob = options ? new Blob([file], options) : new Blob([file])
      eleLink.href = URL.createObjectURL(blob)
      // 触发点击
      document.body.appendChild(eleLink)
      eleLink.click()
      // 然后移除
      document.body.removeChild(eleLink)
    },
    getTaskListData() {
      queryTaskFill({ ...this.page, ...this.params }).then((res) => {
        if (res.success) {
          this.tableData = res.data.list
          this.page.total = res.data.count
          this.multipleSelection = []
        }
      })
    },
    handleRemove(row) {
      addTaskApply({
        resourceId: row.pkid, //资源id
        applyStatus: 1, //-1退回修改，0未审核，1通过
        applyCause: '', //审核理由
      }).then((val) => {
        Message.success(val.data)
        this.getTaskListData()
      })
    },
    goEdit(pkid, isEdit = false, fillStatus, regionId, taskId) {
      this.$router.push({
        name: 'fillInEdit',
        query: { pkid, isEdit, fillStatus, regionId, taskId },
      })
    },
  },
  computed: {
    ...mapGetters(['currentUser', 'user']),
  },
  watch: {
    page(newVal, oldVal) {
      if (
        !(
          newVal.pageIndex === oldVal.pageIndex &&
          newVal.pageSize === oldVal.pageSize
        )
      ) {
        this.getTaskListData()
      }
    },
    params: {
      handler: function () {
        {
          if (this.page.pageIndex === 1) {
            this.getTaskListData()
          } else {
            this.page.pageIndex = 1
            this.getTaskListData()
          }
        }
      },
      deep: true,
    },
  },
}
</script>

<style lang="scss" scoped>
.publish-content {
  // width: calc(100% - 40px);
  // height: calc(100% - 40px);
  padding: 20px;
  width: 100%;
  height: 100%;
  border-radius: 10px;
  box-sizing: border-box;

  .head {
    display: flex;
    justify-content: space-between;
    padding-bottom: 10px;
  }

  .search {
    .el-select {
      margin-right: 10px;
      width: 120px;
    }

    .el-input {
      width: 230px;
    }
  }
}
</style>
